from sys import argv                                                                                                                                                             import os

from banners import HELP_BANNER

def main(argv):
    global HELP_BANNER
    global LENGTH, CHARS, SRC, USE_PRINT, REVERSE

    parse_args(argv)

    replaced = {
        '{1}': LENGTH,
        '{2}': CHARS,
        '{3}': 'count = pow(max_code, length)\n    char_codes = [0] * length\n',
        '{4}': 'range_ = range(length)\n',
        '{-1}': 'for code in char_codes:\n            print(chars[code], end="")\n        print()',
        '{-2}': 'char_codes[0] += 1\n        for i in range_:\n            if char_codes[i] == max_code:\n                if i+1 < length:\n                    char_codes[i+1] +
= 1\n                char_codes[i] = 0'
    }

    # Базовый код программы с выводом результата в консоль
    base_code = open('base_code.py').read()                                                                                                                                      
    # Строчки кода, которые нужно заменить относительно значений
    # флагов. Например, если нужен вывод результата в консоль, то
    # в базовом коде "&1" заменится на вывод                                                                                                                                     
    if '\'' in CHARS:
        if '"' in CHARS:
            CHARS = CHARS.replace('\'', '\\\'')
            CHARS = '\'' + CHARS + '\''
        else:
            CHARS = '"' + CHARS + '"'
    else:
        CHARS = '\'' + CHARS + '\''

    if SRC:
        USE_SRC = True
        if '\'' in SRC:
            if '"' in SRC:
                SRC = SRC.replace('\'', '\\\'')
                SRC = '\'' + SRC + '\''
            else:
                SRC = '"' + SRC + '"'
        else:
            SRC = '\'' + SRC + '\''
    else:
        USE_SRC = False

    replaced['{2}'] = CHARS
    replaced['{3}'] = replaced['{3}'].replace('{SRC}', SRC)

    if not USE_PRINT:
        replaced['{-1}'] = ''

    if REVERSE:
        replaced['{4}'] = 'range_ = range(1, length)\n'
        replaced['{-2}'] = 'char_codes[-1] += 1\n        for i in range_:\n            if char_codes[-i] == max_code:\n                if i+1 < length:\n                    char
_codes[-i-1] += 1\n                char_codes[-i] = 0'

    if USE_SRC:
        replaced['{3}'] = f'src = {SRC}\n\n    char_codes = [chars.index(char) for char in src]\n    count, level = 0, 0\n    for i in char_codes:\n        if i != 0:\n
   value = i\n            count += value * pow(max_code, level)\n        level += 1\n    count = pow(len(chars), length) - count\n'

    for i in replaced.keys():
        base_code = base_code.replace(i, replaced[i])

    with open('program.py', 'w') as f:
        f.write(base_code)

def parse_args(argv):
    global LENGTH, CHARS, SRC, USE_PRINT, REVERSE
    global HELP_BANNER
    ptr = 0                                                                                                                                                                          count_args = len(argv)                                                                                                                                                           while ptr < count_args:
        arg = argv[ptr]
        if arg == 'set' and ptr == 0:
            ptr += 1
            if ptr == count_args:
                print('Missing first argument: LENGHT')
                exit()
            LENGTH = argv[ptr]
            ptr += 1
            if ptr == count_args:
                print('Missing second argument: CHARS')
                exit()
            CHARS = argv[ptr]
            ptr += 1
            if ptr == count_args:                                                                                                                                                                print('Missing third argument: SRC')
                exit()
            SRC = argv[ptr]
        elif arg == 'run' and ptr == 0:
            os.system('python3 program.py')
            exit()
        elif arg == 'help' and ptr == 0:
            print(HELP_BANNER)
            exit()
        elif arg == '-p' or arg == '--print':
            USE_PRINT = True
        elif arg == '-r' or arg == '--reverse':
            REVERSE = True
        ptr += 1

# Флаги
USE_PRINT = False
REVERSE = False

# Обязательные аргументы, кроме SRC
LENGTH = 0
CHARS = ''
SRC = ''

main(argv[1:])